package com.carrental.servlet;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.carrental.entity.User;
import com.carrental.service.UserService;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	UserService userService;
       
    /**
     * @throws Exception 
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() throws Exception {
        super();
        userService = new UserService();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String password2 = request.getParameter("password2");
		String phone = request.getParameter("phone");

		User user = new User();
		user.setUsername(username);
		user.setPassword(password2);
		user.setPhone(phone);
		user.setCreateDatetime(new Timestamp(new Date().getTime()));
		
		System.out.println("添加用户：" + user);
		
		if (!password.equals(password2)) {
			System.out.println("添加用户：密码不一致，" + user);
			response.sendRedirect("register.jsp?code=1002");
		} else {
			try {
				User selectByUsername = userService.selectByUsername(username);
				if (selectByUsername != null) {
					System.out.println("添加用户：用户名已存在，" + user);
					response.sendRedirect("register?code=0001");
				} else {
					userService.add(user);
					response.sendRedirect("register.jsp?code=0000");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
